package com.abc.bootbycustomloader.loader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * created by CaiBaoHong at 2018/6/26 11:37<br>
 */
public class MyResourceLoader extends DefaultResourceLoader {

    private static final Logger log = LoggerFactory.getLogger(MyResourceLoader.class);

    private Map<String,Class<?>> map = new HashMap<>();

    private ClassLoader cl = new ClassLoader() {
        @Override
        public Class<?> loadClass(String name) throws ClassNotFoundException {
            if (name.equals("com.abc.bootbycustomloader.controller.UserController")) {
                System.out.println("!!!!!加密的: "+name);
                if(map.get("name")!=null){
                    return map.get(name);
                }else{
                    String path = "D:\\_clz\\UserController.class";
                    byte[] data = new byte[0];
                    try {
                        data = Files.readAllBytes(Paths.get(path));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    Class<?> clz = defineClass(name, data, 0, data.length);
                    map.put(name,clz);
                    return clz;
                }
            } else {
                //System.out.println("不是加密的： " + name);
                return super.loadClass(name);
            }



        }
    };

    public MyResourceLoader() {
        Thread.currentThread().setContextClassLoader(cl);
    }



    @Override
    public Resource getResource(String location) {
        return super.getResource(location);
    }


    @Override
    public ClassLoader getClassLoader() {
		return cl;
    }

}
